﻿using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;

public partial class UserAppointments : System.Web.UI.Page
{
    DataSet ds = new DataSet();
    MySqlCommand cmd = new MySqlCommand();
    MySqlConnection con;
    public static string loggedInUserName = "";
    public static string loggedInUserType = "";

    static string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["LoginName"] == null || Session["UserId"] == null)
        {
            Response.Redirect("Home.aspx");
        }
        else
        {
            if (!IsPostBack)
            {
                loggedInUserType = Session["UserType"].ToString();
                loggedInUserName = Session["LoginName"].ToString();
                FillDropdowns();
                BindUserAppointmentData();
            }
        }
    }

    private void FillDropdowns()
    {
        ArrayList groups = new ArrayList();
        ArrayList allGroups = new ArrayList();

        if (Session["UserTypeId"] != null)
            groups = EventDAO.getGroups(Convert.ToInt32(Session["UserTypeId"]), Convert.ToInt32(Session["level"]));

        allGroups.Add("Select group");
        allGroups.AddRange(groups);

        addGroups.DataSource = allGroups;
        addGroups.Items.Insert(0, new ListItem("Select group"));
        addGroups.DataBind();
    }

    public void BindUserAppointmentData()
    {
        con = new MySqlConnection(connectionString);

        ArrayList groups = new ArrayList();

        if (Session["UserTypeId"] != null)
            groups = EventDAO.getGroups(Convert.ToInt32(Session["UserTypeId"]), Convert.ToInt32(Session["level"]));

        int level = Convert.ToInt32(Session["level"]);
        string loggedInUser = Convert.ToString(Session["LoginName"]);

        DataTable dt = EventDAO.getUsersAppointments(loggedInUser, level);
        ViewState["dt"] = dt;
        Grid.DataSource = dt;
        Grid.DataBind();
        con.Close();
    }

    public void OnExportGridToCSV(object sender, System.EventArgs e)
    {
        // Create the CSV file to which grid data will be exported.
        StreamWriter sw = new StreamWriter(Server.MapPath("~/Appointments.csv"), false);
        // First we will write the headers.
        DataTable dt = ((DataSet)Grid.DataSource).Tables[0];

        int iColCount = dt.Columns.Count;
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dt.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);
        // Now write all the rows.
        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    sw.Write(dr[i].ToString());
                }
                if (i < iColCount - 1)
                {
                    sw.Write(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator);
                }
            }
            sw.Write(sw.NewLine);
        }
    }

    protected void imgBtnDownload_Click(object sender, ImageClickEventArgs e)
    {
        //string CsvFpath = "C:\\Appointments.csv";
        string CsvFpath = Server.MapPath("~/appointments.csv");

        try
        {
            StreamWriter sw = new StreamWriter(CsvFpath, false);
            DataTable dt = (DataTable)ViewState["dt"];

            int iColCount = dt.Columns.Count;
            for (int i = 0; i < iColCount; i++)
            {
                sw.Write(dt.Columns[i]);
                if (i < iColCount - 1)
                    sw.Write(",");
            }

            sw.Write(sw.NewLine);
            foreach (DataRow dr in dt.Rows)
            {
                for (int i = 0; i < iColCount; i++)
                {
                    if (!Convert.IsDBNull(dr[i]))
                        sw.Write(dr[i].ToString());
                    if (i < iColCount - 1)
                        sw.Write(",");
                }
                sw.Write(sw.NewLine);
            }
            sw.Close();

            Response.Clear();
            Response.ContentType = "application/csv";
            Response.AddHeader("Content-Disposition", "attachment; filename=appointments.csv");
            Response.WriteFile(CsvFpath);
            Response.Flush();
            Response.End();

            //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "key_name", "alert('The requested file has been downloaded to C:\\Appointments.csv');", true);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    protected void addGroups_SelectedIndexChanged(object sender, EventArgs e)
    {
        string selGroupName = this.addGroups.SelectedItem.Text;
        ArrayList users = EventDAO.getUsersForAGroup(selGroupName);
        ArrayList usersToBind = new ArrayList();

        string[] strings = Array.ConvertAll<object, string>(users.ToArray(), Convert.ToString);
        if (loggedInUserType != null && loggedInUserType.Equals(selGroupName))
        {
            usersToBind.Add(loggedInUserName);
        }
        else
        {
            for (int i = 0; i < strings.Length; i++)
            {
                usersToBind.Add(strings[i].ToString());
            }
        }

        addUsers.DataSource = usersToBind;
        addUsers.DataBind();
    }

    protected void btnFilterByDate_Click(object sender, EventArgs e)
    {
        if (txtFrom.Text == null || txtTo.Text == null || txtFrom.Text.Trim().Equals(String.Empty) || txtTo.Text.Trim().Equals(String.Empty))
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "key_name", "alert('From/To date cannot be null or empty.');", true);
        }
        else
        {
            if (Convert.ToDateTime(txtFrom.Text) <= Convert.ToDateTime(txtTo.Text))
            {
                addGroups.SelectedIndex = 0;
                addUsers.Items.Clear();

                int level = Convert.ToInt32(Session["level"]);
                string loggedInUser = Convert.ToString(Session["LoginName"]);

                DataTable dt = EventDAO.getDatesAppointments(loggedInUser, level, Convert.ToDateTime(txtFrom.Text), Convert.ToDateTime(txtTo.Text));

                ViewState["dt"] = dt;
                Grid.DataSource = dt;
                Grid.DataBind();
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "key_name", "alert('From date cannot be greater than To date.');", true);
            }
        }
    }

    protected void btnFilterByGroup_Click(object sender, EventArgs e)
    {
        if (this.addGroups.SelectedItem != null)
        {
            string selGroupName = "";
            int level = Convert.ToInt32(Session["level"]);
            string loggedInUser = Convert.ToString(Session["LoginName"]);
            DataTable dt = new DataTable();

            if (this.addGroups.SelectedIndex != 0)
            {
                selGroupName = this.addGroups.SelectedItem.Text;
                dt = EventDAO.getGroupsAppointments(loggedInUser, level, selGroupName);
            }
            else
            {
                selGroupName = "";
                dt = EventDAO.getUsersAppointments(loggedInUser, level);
            }

            ViewState["dt"] = dt;
            Grid.DataSource = dt;
            Grid.DataBind();
        }
    }

    protected void btnFilterByUser_Click(object sender, EventArgs e)
    {
        //DataTable dt = (DataTable)ViewState["dt"];
        txtFrom.Text = "";
        txtTo.Text = "";
        if (this.addUsers.SelectedItem != null)
        {
            string selUserName = this.addUsers.SelectedItem.Text;

            int level = Convert.ToInt32(Session["level"]);
            DataTable dt = EventDAO.getOnlyUsersAppointments(selUserName, level);

            ViewState["dt"] = dt;
            Grid.DataSource = dt;
            Grid.DataBind();
        }
    }
}
